package com.jingdun.sport.api.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jingdun.sport.bean.model.*;
import com.jingdun.sport.common.constants.RedisConstants;
import com.jingdun.sport.common.util.PageParam;
import com.jingdun.sport.service.TrendsChatService;
import com.jingdun.sport.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/sport/trendschat/")
@Api(tags = "动态评论")
public class TrendsChatController {

    @Autowired
    private TrendsChatService trendsChatService;

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 添加评论
     */
    @PostMapping("/addTrendsChat")
    @ApiOperation(value = "添加评论", notes = "添加评论")
    public ResponseEntity<ApiResult> addTrendsChat(@RequestBody TrendsChat trendsChat) {
        trendsChat.setGmtCreate(new Date());

        if (trendsChatService.save(trendsChat)) {
            return ResponseEntity.status(200).build();
        }
        return ResponseEntity.status(201).build();
    }

    /**
     * 添加评论
     */
    @GetMapping("/listTrendsChat")
    @ApiOperation(value = "评论列表", notes = "评论列表")
    public ResponseEntity<IPage> listTrendsChat(Long trendsId, PageParam pageParam) {
        long current = pageParam.getCurrent();
        pageParam.setCurrent((pageParam.getCurrent() - 1) * pageParam.getSize());
        List<TrendsChat> trendsChatList = trendsChatService.pageList(trendsId, pageParam);
        trendsChatList.stream().forEach(records -> {
            User user = userService.getById(records.getUserId());
            records.setPic(user.getPic());
            records.setNickName(user.getNickName());
        });
        trendsChatList.sort((t1, t2) -> t2.getGmtCreate().compareTo(t1.getGmtCreate()));
        pageParam.setRecords(trendsChatList);
        pageParam.setCurrent(current);
        return ResponseEntity.ok(pageParam);
    }
}
